import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-07-17
 * Time: 2:35
 */
//https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
//给你一棵二叉树的根节点 root ，返回其节点值的 后序遍历 。(使用非递归方法)
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
    public void print(){
        System.out.print(val+" ");
        if(left!=null){
            left.print();
        }
        if(right!=null){
            right.print();
        }
    }
}
public class Test {
    public static List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        if(root==null){
            return list;
        }
        TreeNode p=root;
        TreeNode n=null;
        Stack<TreeNode> stack=new Stack();
        while(p==root||!stack.isEmpty()){
            while(p!=null){
                stack.push(p);
                p=p.left;
            }
            p=stack.peek();
            while(p.right==null){
                list.add(p.val);
                n=p;
                stack.pop();
                if(stack.isEmpty()){
                    break;
                }
                p=stack.peek();
            }
            if(stack.isEmpty()){
                break;
            }
            while(p.right==n){
                list.add(p.val);
                n=p;
                stack.pop();
                if(stack.isEmpty()){
                    break;
                }
                p=stack.peek();
            }
            if(stack.isEmpty()){
                break;
            }
            p=p.right;
        }
        return list;
    }

    public static void main(String[] args) {
        TreeNode A1=new TreeNode(1);
        TreeNode A2=new TreeNode(2);
        TreeNode A3=new TreeNode(3);
        TreeNode A4=new TreeNode(4);
        TreeNode A5=new TreeNode(5);
        TreeNode A6=new TreeNode(6);
        TreeNode A7=new TreeNode(7);
        A1.right=A2;
        A2.left=A3;
        ArrayList list=(ArrayList)postorderTraversal(A7);
        System.out.println(list.toString());
    }
}
